package com.dragonfly.shutter.controllers;

import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.bind.support.SessionStatus;
import org.springframework.web.servlet.ModelAndView;

import com.dragonfly.shutter.DAOIbatisImpls.UserDAOIbatisImpl;
import com.dragonfly.shutter.beans.UserLogin;
import com.dragonfly.shutter.validator.LoginValidator;

/**
 * 用户登录的控制器
 * @author 王长乐
 *
 */
@Controller
@SessionAttributes({"userID","validateCode"})
@RequestMapping("/login.html")
public class LoginController {
	@Autowired
	private UserDAOIbatisImpl userDAO;
	@Autowired
	private LoginValidator loginValidator;
	
	@RequestMapping(method = RequestMethod.GET)
	public String setupForm(ModelMap model
			)
	{
		UserLogin userLogin=new UserLogin();
		model.addAttribute(userLogin);
		return "login";

	}

	@RequestMapping(method = RequestMethod.POST)
	public ModelAndView processSubmit(ModelMap model,
	               @ModelAttribute("userLogin")UserLogin userLogin, 
	               BindingResult result,
	               @ModelAttribute("validateCode") String validateCode,
	                   SessionStatus status, HttpSession session)
	{
	       
		if (!validateCode.equals(userLogin.getValidateCode().toUpperCase())) 
		{
			result.rejectValue("validateCode", "validator.error", "验证码不正确");
			return new ModelAndView("login");
		}
		
			loginValidator.validate(userLogin, result);
			
			if(result.hasErrors())
			{
			        return new ModelAndView("login");
			}
			else
			{
				UserLogin UId=userDAO.selectLoginInfoByEmail(userLogin.getEmail());//@TODO：通过邮箱得到用户ID

				session.setAttribute("userID", UId.getUserID());
				
				return new ModelAndView("redirect:/user.html?userID="+UId.getUserID());
				
			}
	       
	}
			
		}
		
	

	
